<template>
  <div class="ma-content-block  p-4">
    <div class="flex justify-between home-page-title " style="margin-bottom:2%">
      <div style="text-align:center;padding:0 16px 0 14px">时间选择</div>
      <div class="ma-content-block rounded-sm flex justify-between w-full " style="flex:1;width:0">
        <div class="datetime  flex">
          
          <template  v-for="(item, index) in tags"
              :key="index">
            <span
              v-if='item.falg'
              @click="changeTime(index)"
              :class="{ active: index == currentTag }"
            >
            {{ item.name }}
              
            </span>
          </template>
          <a-range-picker
            style="width: 268px"
            v-model="rangeValue"
            @change="onChange"
          >
            <span
              @click="changeTime(tags.length)"
              :class="{ active: currentTag == tags.length }"
            >
              自定义
            </span>
          </a-range-picker>
        </div>
      </div>
    </div>
    <!-- CRUD 组件 -->
    <ma-crud :options="options" :columns="columns" ref="crudRef">
        <template #operationAfterExtend="{ record }">
            <a-button type="primary" @click="handleDetail(record)">详情</a-button>
        </template>
    </ma-crud>
    <div class='lg:flex'>
        <div style='width:300px'>小计：{{xiaoji.toFixed(2)}}</div>
        <div>合计：{{heji}}</div>
    </div>
    <!-- 结算详情 -->
    <a-modal :mask-closable="false"  v-model:visible="showModle" title="结算详情" v-if='showModle' @cancel="handleYujiCel" :width="1400" :footer="false">
      <a-row :gutter="16" style="margin-bottom:2%">
            <a-col :span="6">
                <div class="flex " style="align-items:center">
                  <div style="width:86px;text-align:center">付款方:</div>
                  <a-input  v-model="datailObj.qsgs" placeholder="请输入付款方" :disabled="true" ></a-input>
                </div>
            </a-col>
            <a-col :span="6">
                <div class="flex " style="align-items:center">
                  <div style="width:86px;text-align:center">收款方:</div>
                  <a-input  v-model="datailObj.skgs" placeholder="请输入收款方" :disabled="true" ></a-input>
                </div>
            </a-col>
            <a-col :span="6">
                <div class="flex " style="align-items:center">
                  <div style="width:86px;text-align:center">结算比例:</div>
                  <a-input  v-model="datailObj.bili" placeholder="请输入结算比例" :disabled="true" >
                        
                    </a-input>
                </div>
            </a-col>
            <a-col :span="6">
                <div class="flex " style="align-items:center">
                  <div style="width:86px;text-align:center">业务所属月份:</div>
                  <a-input  v-model="datailObj.fz_date" placeholder="暂无月份" :disabled="true" >
                    </a-input>
                </div>
            </a-col>
      </a-row>
      <a-row :gutter="16" style="margin-bottom:2%">
          <a-col :span="24">
            <div class="flex" >
              <div style="width:75px;text-align:center">备注:</div>
              <a-textarea v-model="datailObj.remark" placeholder="请输入备注" :disabled="true"/>
            </div>
          </a-col>
      </a-row>
      <a-table :columns="columnsTable" :data="datailObj.info" >
            <template #pay_type="{ record }">
                <div>{{ record.pay_type=='money'?'预付款':record.pay_type=='periodic'?'周期结算':'现结' }}</div>
            </template>
            <template #now_pay_type="{ record }">
                <div>{{ record.now_pay_type=='1'?'惠支付':record.now_pay_type=='2'?'现金':record.now_pay_type=='3'?'对公转账':'' }}</div>
            </template>
            <template #pay_price="{ record }">
              <a-popover :title="`收费明细（合计金额：${record.pay_price}）`" position="right">
                  <a-link >{{record?.pay_price}}</a-link>
                  <template #content>
                    <div style='min-width:300px'>
                      <a-table :columns="tablecolumnsts" :data="record.detail" :pagination='false' :span-method="spanMethodAll" :bordered="{wrapper: true, cell: true}" />
                    </div>
                  </template>
              </a-popover>
            </template>
      </a-table>
      <div class='lg:flex'>
        <div style='width:150px'>共计{{datailObj.info.length}}条</div>
        <div style='width:300px'>合计：交易金额{{datailObj.money}}元</div>
        <div>结算金额{{datailObj.js_price}}元</div>
    </div>
    </a-modal>
  </div>
</template>
<script setup>
import { ref, reactive } from 'vue'
import { request } from "@/utils/request.js";
import financialMoneyFz from '@/api/financial/financialMoneyFz'
import { Message } from '@arco-design/web-vue'
import tool from '@/utils/tool'
import * as common from '@/utils/common'
import timeFormat from "@/utils/timeFormat.js";
const showModle = ref(false)
const datailObj = ref({})
// 标签
const tags = ref([
  {name:"今天",falg:false},
  {name:"昨天",falg:false},
  {name:"本周",falg:false},
  {name:"本月",falg:true},
  {name:"本季度",falg:true},
  {name:"本年",falg:true},
]);
// 当前标签
const currentTag = ref(3);
// 传入的时间
const currentTime = ref([]);
// 默认时间
currentTime.value = [timeFormat(new Date().getTime(),'yyyy-mm-dd'),timeFormat(new Date().getTime(),'yyyy-mm-dd')]
// 当前时间
const newDate = new Date();
// 当年
const newYear = newDate.getFullYear();
// 当月
const newMonth = newDate.getMonth() + 1;
// 本季度开始月份
const newJDMonth = Math.ceil((newMonth) / 3);
// 今天
const newDay = newDate.getDate();
// 昨天
const oldDay = timeFormat(new Date(newDate).setDate(newDate.getDate() - 1),'yyyy-mm-dd');
// 明天
const minDay = timeFormat(new Date(newDate).setDate(newDate.getDate() + 1),'yyyy-mm-dd');
// 本月天数
const newMaxDay = new Date(newYear, newMonth, 0).getDate();
// 本周一的日期
const newMonday = new Date(
  newDate.setDate(newDate.getDate() - newDate.getDay() + 1)
).getDate();
// 本周日的日期
const newSunday = new Date(newDate.setDate(newDate.getDate() + 6)).getDate();
const xiaoji = ref(0)
const heji = ref(0)
const crudRef = ref()
const handleDetail = (obj)=>{
  if(obj.info){
    obj.info.map((v,i)=>{
      v.qsgs = obj.qsgs
    })
  }
  datailObj.value = obj
  showModle.value = true
}
const onChange = (e) => {
		currentTime.value = e
    crudRef.value.refresh()
	};

const changeTime = (index) => {
  currentTag.value = index;
  if (index !== tags.value.length) {
  	initTime(index);
    crudRef.value.refresh()
  	return;
  }
};
const handleYujiCel = ()=>{
  showModle.value = false
}
const initTime = (index) => {
  switch (index) {
    // 默认 今日
    case 0:
      currentTime.value[0] = `${newYear}-${newMonth}-${newDay}`;
      currentTime.value[1] = `${minDay}`;
      break;
    //昨日
    case 1:
      currentTime.value[0] = `${oldDay}`;
      currentTime.value[1] = `${newYear}-${newMonth}-${newDay}`;
      break;
    // 本周
    case 2:
      currentTime.value[0] = `${newYear}-${newMonth}-${newMonday}`;
      currentTime.value[1] = `${newYear}-${newMonth}-${newSunday}`;
      break;
    // 本月
    case 3:
      currentTime.value[0] = `${newYear}-${newMonth}-01`;
      currentTime.value[1] = `${newYear}-${newMonth}-${newMaxDay}`;
      break;
    // 本季度
    case 4:
      currentTime.value[0] = `${timeFormat(new Date(newYear, (newJDMonth-1)*3, 1),'yyyy-mm-dd')}`;
      currentTime.value[1] = `${timeFormat(new Date(newYear, newJDMonth*3, 0),'yyyy-mm-dd')}`;
      break;
    // 本年
    case 5:
      currentTime.value[0] = `${newYear}-01-01`;
      currentTime.value[1] = `${newYear}-12-31`;
      break;
  }
};
const numberOperation = (newValue, id, numberName) => {
  financialMoneyFz.numberOperation({ id, numberName, numberValue: newValue }).then( res => {
    res.success && Message.success(res.message)
  }).catch( e => { console.log(e) } )
}

const switchStatus = (statusValue, id, statusName) => {
  financialMoneyFz.changeStatus({ id, statusName, statusValue }).then( res => {
    res.success && Message.success(res.message)
  }).catch( e => { console.log(e) } )
}
const tablecolumnsts = [
      {
        title: '车号',
        dataIndex: 'car_nos',
      },
      {
        title: '收费项目',
        dataIndex: 'pay_name',

      },
      {
          title: '不含税金额',
          dataIndex: 'no_tax_price',
      },
      {
          title: '税额',
          dataIndex: 'tax_price',
      },
      {
        title: '原金额',
        dataIndex: 'pay_price',
      },
      {
        title: '实际金额',
        dataIndex: 'pay_real_price',
      },
      {
          title: '优惠金额',
          dataIndex: 'discount_price',
      },
      {
        title: '天-D',
        dataIndex: 'day',
      },
      {
        title: '吨-T',
        dataIndex: 'weight',
      },
      {
        title: '车-C',
        dataIndex: 'car_no_value',
      },
      {
        title: '箱-X',
        dataIndex: 'box',
      },
      {
        title: '计费规则',
        dataIndex: 'chi_price_role',
      },
      {
        title: '备注',
        dataIndex: 'remark',
      },
];
const  spanMethodAll= ({record,rowIndex, columnIndex}) => {
    if (rowIndex === record.weizhi - record.weizhizong && columnIndex === 0) {
      return {rowspan: record.weizhizong,colspan:1}
    }
  };
  const handleSOrt = (ceshiArr)=>{
    let arr = []           // 最终数据
    let linshiArr = []     //  未匹配的放数组里
    let linshititle = ''   // 临时变量
    ceshiArr.map((v,i)=>{
      if(i == 0){
        linshititle = v.name
        arr.push(v)
      }else{
        if(linshititle == v.name){
          arr.push(v)
        }else{
          linshiArr.push(v)
        }
      }
    })
    ceshiArr.map((v,i)=>{
      if(linshiArr.length != 0){
        linshiArr.map((vv,ii)=>{
          if(ii == 0){
            linshititle = linshiArr[0].name
            arr.push(linshiArr.shift())
          }else{
            if(linshititle == vv.name){
              arr.push(linshiArr.slice(ii,1))
            }
          }
          
        })
        
      }
    })
    arr.sort((a, b) => a.car_nos.localeCompare(b.car_nos));
    return arr
  }
  const handleObjItem = (params)=>{
    params.map((v, i) => {
			let arr = []
      let arrs = []
      v.detail.map((vv,ii)=>{
        // if(v.prediction_id){  //  到站收费
          vv.car_nos = vv.prediction.car_no
          vv.no_tax_price = (vv.no_tax_price - 0 ).toFixed(2)
          vv.tax_price = (vv.tax_price - 0 ).toFixed(2)
          vv.pay_real_price = (vv.pay_real_price - 0 ).toFixed(2)
          vv.pay_price = (vv.pay_price - 0 ).toFixed(2)
          vv.discount_price = (vv.discount_price - 0 ).toFixed(2)
        // }else{
        //   if(v.prediction_order_id != 0 && v.prediction_driver_order_id == 0){  //  补费
        //     vv.car_nos = ''
        //   }else{  // 装车收费
        //     if(vv.order_detail.prediction_id == 0){
        //       vv.car_nos = vv.order_detail.wareuserdetail.car_no
        //     }else{
        //       vv.car_nos = vv.order_detail.prediction.car_no
        //     }
        //   }
          
        // }
        if(vv.pay_price != '0.00' && vv.is_confirm ==  1){
          arr.push(vv)
        }
      })
      
      v.detail = handleSOrt(arr)
      let carArr = []
      v.detail.map((vv,ii)=>{
        carArr.push(vv.car_nos)
      })
      var newArr = carArr.filter(function(item,index){
        return carArr.indexOf(item) === index;  // 因为indexOf 只能查找到第一个  
      });
      let numArr = []
      newArr.map((vv,ii)=>{
        let num = 0
        let name = ''
        carArr.map((vvv,iii)=>{
          if(vv == vvv){
            num++
            name = vvv
          }
        })
        numArr.push({car_no:name,weizhi:num,weizhizong:num})
      })
      let weizhiArr = []
      let weizhinum = 0
      numArr.map((vv,ii)=>{
        weizhinum += vv.weizhi
        weizhiArr.push({car_no:vv.car_no,weizhi:weizhinum,weizhizong:vv.weizhizong})
      })
      v.detail.map((vv,ii)=>{
        weizhiArr.map((vvv,iii)=>{
          if(vv.car_nos == vvv.car_no){
            vv.weizhi = vvv.weizhi
            vv.weizhizong = vvv.weizhizong
          }
        })
      })
      
		});
    return params
  }
const options = reactive({
  id: 'flyos_financial_money_fz',
  rowSelection: {
    showCheckedAll: true
  },
  pk: 'id',
  operationColumn: true,
  isDbClickEdit:false,
  operationWidth: 160,
  formOption: {
    viewType: 'modal',
    width: 600
  },
  api: financialMoneyFz.getList,
  recycleApi: financialMoneyFz.getRecycleList,
  add: {
    show: false,
    api: financialMoneyFz.save,
    auth: ['financial:moneyFz:save']
  },
  edit: {
    show: false,
    api: financialMoneyFz.update,
    auth: ['financial:moneyFz:update']
  },
  delete: {
    show: false,
    api: financialMoneyFz.deletes,
    auth: ['financial:moneyFz:delete'],
    realApi: financialMoneyFz.realDeletes,
    realAuth: ['financial:moneyFz:realDeletes']
  },
  recovery: {
    show: false,
    api: financialMoneyFz.recoverys,
    auth: ['financial:moneyFz:recovery']
  },
  import: {
    show: false,
    url: 'financial/moneyFz/import',
    templateUrl: 'financial/moneyFz/downloadTemplate',
    auth: ['financial:moneyFz:import']
  },
  export: {
    show: true,
    url: 'financial/moneyFz/export',
    auth: ['financial:moneyFz:export']
  },
  beforeRequest: (params) => {
        initTime(currentTag.value)
        params.created_at = currentTime.value;
        request({
          url:'financial/moneyFz/total',
          method: 'get',
          params,
        }).then(res=>{
          heji.value = res.data.total
        })
	},
  afterRequest: (params) => {
    let number = 0
    params.map((v, i) => {
      number += (v.money - 0)
      v.bili = ((v.bili - 0) / 100).toFixed(2)
      v.js_price = 0
      let arr = []
      v.detail.map((vv,ii)=>{
        vv.car_nos = vv.prediction.car_no
        if(vv.is_confirm == 1){
          arr.push(vv)
        }
      })
      v.detail = arr
      if(v.info.length != 0){
        handleObjItem(v.info)
        v.info.map((vv,ii)=>{
          let arr = []
          vv.jiesuanprice = ((vv.pay_price - 0) * (v.bili - 0)).toFixed(2)
          v.js_price += (vv.jiesuanprice - 0)
          vv.bili = ((v.bili - 0) * 100) + '%'
        })
      }
      v.bili = ((v.bili - 0) * 100) + '%'
      v.js_price = v.js_price.toFixed(2)
    });
    
    xiaoji.value = number
  },
})
const columnsTable = reactive([
    
    {
      title: "签署公司",
      dataIndex: "qsgs",
      align:'center'
    },
    {
      title: "客户名称",
      dataIndex: "dept.name",
      align:'center'
    },
    
    {
      title: "交易金额",
      dataIndex: "pay_price",
      align:'center',
      slotName:'pay_price'
    },
    {
      title: "结算比例",
      dataIndex: "bili",
      align:'center'
    },
    {
      title: "结算金额",
      dataIndex: "jiesuanprice",
      align:'center'
    },
    {
      title: "支付方式",
      dataIndex: "pay_type",
      slotName:'pay_type'
    },
    {
      title: "现结支付类型",
      dataIndex: "now_pay_type",
      align:'center',
      slotName:'now_pay_type'
    },
    {
      title: "交易时间",
      dataIndex: "pay_date",
      align:'center',
    },
    {
      title: "交易单号",
      dataIndex: "order_number",
      align:'center'
    },
    {
      title: "关联订单",
      dataIndex: "prediction_order_number",
      align:'center'
    },
  ])
const columns = reactive([
  {
    title: "",
    dataIndex: "id",
    formType: "input",
    addDisplay: false,
    editDisplay: false,
    hide: true,
    commonRules: {
      required: true,
      message: "请输入"
    }
  },
  {
    title: "分账单号",
    dataIndex: "order_no",
    formType: "input",
    search: true,
    align:'center',
  },
  {
    title: "交易金额",
    dataIndex: "money",
    formType: "input",
    // search: true,
    align:'center',
  },
  {
    title: "付款方",
    dataIndex: "qsgs",
    formType: "select",
    search: true,
    align:'center',
    dict: {
        data: [
          {value:'威斯腾',label:'威斯腾'},
        ],
        translation: true
      }
  },
  {
    title: "收款公司",
    dataIndex: "skgs",
    formType: "select",
    search: true,
    align:'center',
    dict: {
        data: [
          {value:'威斯腾',label:'威斯腾'},
        ],
        translation: true
      }
  },
  {
    title: "结算比例",
    dataIndex: "bili",
    formType: "input",
    search: true,
    align:'center',
  },
  {
    title: "业务所属月份",
    dataIndex: "fz_date",
    formType: "input",
    search: true,
    align:'center',
  },
  
  {
    title: "结算信息",
    dataIndex: "info",
    formType: "input",
    hide: true,
    align:'center',
  },
  {
      title: "结算时间",
      dataIndex: "created_at",
      formType: "range",
      addDisplay: false,
      editDisplay: false,
      search: false,
      align:'center',
      showTime: true,
    },
  {
    title: "备注",
    dataIndex: "remark",
    formType: "input",
    addDisplay: false,
    editDisplay: false,
    align:'center',
  },
  
])
</script>
<style scoped lang="less">
	.home-page-title {
		align-items: center !important;

		img {
			height: 30px;
		}

		.datetime {
			align-items: center;

			p {
				font-size: 20px;
				color: #415b73;
				margin-left: 20px;
				font-style: italic;
			}

			span {
				width: 64px;
				border-radius: 32px;
				padding: 4px 0;
				display: flex;
				justify-content: center;
				align-items: center;
				margin-right: 20px;
				color: #00a0e9;
				border: 1px solid #00a0e9;
                font-size: 14px;
                font-weight: 400;
				cursor: pointer;

				&.active {
					background: #00a0e9;
					color: #fff;
				}
			}
		}
	}
</style>
<script> export default { name: 'financial:moneyFz' } </script>